-module(node).
-behaviour(application).
-behaviour(supervisor).

%% supervisor exports
-export([init/1]).

%% application exports
-export([start/2, stop/1]).

%% supervisor
init([]) ->
    Tracer = {
        make_ref(),                  %% server id
        {tracer, start_link, []},    %% start function
        permanent,                   %% restart
        100,                         %% shutdown delay
        worker,                      %% type
        [tracer]                     %% module
    },
    RestartStrategy = {one_for_one, 10, 60},

    %% Start as many tracer instances as the number of processors
    %% that are available.
    Tracers = case erlang:system_info(logical_processors) of
        unknown -> [Tracer];
        NumProcs ->
            [setelement(1, Child, make_ref()) || Child <- lists:duplicate(NumProcs, Tracer)]
    end,
    {ok, {RestartStrategy, Tracers}}.

%% application
start(_StartType, _Args) ->
    {ok, Manager} = application:get_env(node, trace_manager),
    case net_kernel:connect_node(Manager) of
        true ->
            global:sync(),
            supervisor:start_link({local, node_supervisor}, node, []);
        _Any ->
            error_logger:error_msg("Error connecting to the manager at ~p.~n", [Manager]),
            {error, no_manager}
    end.
    
stop(_State) ->
    ok.
